<?php
namespace app\conmon;

require_once (dirname(__FILE__) .'/lib/YLYTokenClient.php');
require_once (dirname(__FILE__).'/lib/YLYOpenApiClient.php');

class printer
{
    /**
     * 调用打印机
     *
     * @var string
     */
    private $data = '';
    /**
     * 获取token
     *
     */
    public function GetToken(){
        $token = new \YLYTokenClient();
        $grantType = 'client_credentials';  //自有模式(client_credentials) || 开放模式(authorization_code)
        $scope = 'all';                     //权限
        $timesTamp = time();                //当前服务器时间戳(10位)
        //$code = '';                       //开放模式(商户code)
        return  $token->GetToken($grantType,$scope,$timesTamp);
    }
    /**
     * 打印接口
     *
     * @param $order_no 订单号
     * @param $money 总计金额
     * @param $data 商品
     * @param $freight 运费
     * @param $discounts 优惠金额
     */
   public function printIndex($order_no,$money,$data,$freight,$discounts,$name,$phone,$site,$remark,$access_token,$num){
        $api = new \YLYOpenApiClient();
        $content = '';                          //打印内容
        $content .= '<FS><center>铭记掌上超市</center></FS>';
        $content .= '<center>30分钟送货到家</center>';
        $content .= "\n";
        $content .= '订单号: '.$order_no.''."\n";
        $content .= '下单时间: '.date('Y-m-d H:i:s').''."\n";
        $content .= str_repeat('-',32);
        $content .= '<table>';
        $content .= '<tr><td>商品</td><td>数量</td><td>价格</td></tr>';
        foreach ($data as $value){
            $content .= '<tr><td>'.$value['name'].'</td><td>x'.$value['num'].'</td><td>￥'.$value['total_price'].'</td></tr>';
        }
        $content .= '</table>';
        $content .= "\n".str_repeat('-',32)."\n";
        $content .= '运费: '.$freight.'元　　';
        $content .= '优惠: '.$discounts.'元'."\n";
        $content .= '总计数量: x'.$num.''."\n";
        $content .= '总计金额: '.$money.'元';
        $content .= "\n"."\n";
        $content .= '<FS>'.$name.'</FS>';
        $content .= '<FS>'.$phone.'</FS>';
        $content .= "\n".$site;
        $content .= "\n".str_repeat('-',32)."\n";
        if($remark){
            $content .= '备注: '.$remark.'';
        }
        $content .= "\n"."\n";

        $machineCode = '4004533626';                      //授权的终端号
        $accessToken = $access_token;                      //api访问令牌
        $originId = $order_no;                         //商户自定义id
        $timesTamp = time();                    //当前服务器时间戳(10位)
        return $api->printIndex($machineCode,$accessToken,$content,$originId,$timesTamp);
    }
    /**
     * 终端授权
     */
    public function accredit($access_token){
        $api = new \YLYOpenApiClient();
        $machineCode = '4004533626';
        $msign = 'xaervuuhbcqd';
        $accessToken = $access_token;
        return $api->addPrint($machineCode,$msign,$accessToken,$timesTamp = time());
    }
}
